package com.shunda.ysdgj.manager.service.impl.system;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shunda.ysdgj.common.exception.CustomException;
import com.shunda.ysdgj.common.listener.EasyExcelListener;
import com.shunda.ysdgj.common.util.ValidateUtil;
import com.shunda.ysdgj.manager.mapper.system.SysRoleMapper;
import com.shunda.ysdgj.manager.service.system.SysRoleService;
import com.shunda.ysdgj.model.dto.base.IdsDto;
import com.shunda.ysdgj.model.dto.system.SysRoleFindDto;
import com.shunda.ysdgj.model.entity.system.SysRole;
import com.shunda.ysdgj.model.vo.ResultCodeEnum;
import com.shunda.ysdgj.model.vo.system.RoleExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService, IService<SysRole> {

    public List<SysRole> findAll() {
        return lambdaQuery().select(SysRole::getId, SysRole::getRoleName).list();
    }

    public IPage<SysRole> findByPage(SysRoleFindDto sysRoleFindDto) {
        if (ValidateUtil.isNotLong(sysRoleFindDto.getCurrent())) {
            sysRoleFindDto.setCurrent(1L);
        }
        if (ValidateUtil.isNotLong(sysRoleFindDto.getSize())) {
            sysRoleFindDto.setSize(10L);
        }
        LambdaQueryChainWrapper<SysRole> lambdaQuery = lambdaQuery();
        if (StrUtil.isNotEmpty(sysRoleFindDto.getRoleName())) {
            lambdaQuery.like(SysRole::getRoleName, sysRoleFindDto.getRoleName());
        }
        IPage<SysRole> page = new Page<>(sysRoleFindDto.getCurrent(), sysRoleFindDto.getSize());
        return lambdaQuery.page(page);
    }

    public boolean add(SysRole sysRole) {
        if (ValidateUtil.isBlank(sysRole.getRoleName())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        sysRole.setId(null);
        return save(sysRole);
    }

    public boolean modify(SysRole sysRole) {
        if (ValidateUtil.isNotLong(sysRole.getId())
                || ValidateUtil.isBlank(sysRole.getRoleName())) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        return updateById(sysRole);
    }

    @Transactional
    public boolean deleteByIds(IdsDto idsDto) {
        List<Long> ids = idsDto.getIds();
        if (ids.isEmpty()) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        for (long id : ids) {
            if (id == 1) { // id为1的角色是超级管理员，不能删除
                throw new CustomException(ResultCodeEnum.SYSTEM_ROLE_ERROR);
            }
        }
        return removeByIds(ids);
    }

    //TODO 导出excel，为了测试用，以后要删掉
    public void exportToExcel(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("角色数据", StandardCharsets.UTF_8);
            response.setHeader("Content-disposition", String.format("attachment;filename=%s.xlsx", fileName));
            List<SysRole> roleList = lambdaQuery().list();
            List<RoleExcelVo> roleExcelVoList = new ArrayList<>();
            for (SysRole role : roleList) {
                RoleExcelVo roleExcelVo = new RoleExcelVo();
                BeanUtils.copyProperties(role, roleExcelVo);
                roleExcelVoList.add(roleExcelVo);
            }
            EasyExcel.write(response.getOutputStream(), RoleExcelVo.class)
                    .sheet("角色数据").doWrite(roleExcelVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //TODO 从excel导入，为了测试用，以后要删掉
    public void importFromExcel(MultipartFile file) {
        try {
            EasyExcelListener<SysRole, RoleExcelVo> listener = new EasyExcelListener<>(this, SysRole.class);
            EasyExcel.read(file.getInputStream(), RoleExcelVo.class, listener).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
